package com.project.basis.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.project.basis.R;
import com.project.basis.config.ProjectApplication;
import com.project.basis.ui.activity.user.LoginActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToolsUtils {

    public static String passwordRegular = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#$%^&*()_+-=?/]{8,16}$";

    /**
     * 提示空输入框
     */
    public static boolean editTextsHint(final EditText... editTexts) {
        for (int i = 0; i < editTexts.length; i++) {
            if (TextUtils.isEmpty(editTexts[i].getText())) {
                ToastUnits.showShortToast(editTexts[i].getHint());
                return false;
            }
        }
        return true;
    }

    /**
     * 验证码倒计时
     */
    public static CountDownTimer CountDownTime(final Context context, int secondTime, final TextView textView) {
        textView.setEnabled(false);
        return new CountDownTimer(secondTime + 1500, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                textView.setText(String.format(context.getString(R.string.resend_down_time_s), (millisUntilFinished / 1000) - 1));
            }

            @Override
            public void onFinish() {
                textView.setEnabled(true);
                textView.setText(context.getString(R.string.resend));
            }
        }.start();
    }

    /**
     * 判断输入框是否全部填写完毕
     */
    public static void editTextsComplete(final OnInputListener listener, final EditText... editTexts) {
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean isComplete = true;
                for (int i = 0; i < editTexts.length; i++) {
                    if (TextUtils.isEmpty(editTexts[i].getText())) {
                        isComplete = false;
                        break;
                    }
                }
                listener.onComplete(isComplete);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        for (int i = 0; i < editTexts.length; i++) {
            editTexts[i].addTextChangedListener(watcher);
        }
    }


    /**
     * 判断输入框内容是否符合正则
     *
     * @param regular 正则
     */
    public static void editTextsRegularComplete(final String regular, final OnInputListener listener, final EditText... editTexts) {
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean isComplete = true;
                for (int i = 0; i < editTexts.length; i++) {
                    Pattern p = Pattern.compile(regular);
                    Matcher m = p.matcher(s);
                    if (!m.matches()) {
                        isComplete = false;
                        break;
                    }
                }
                listener.onComplete(isComplete);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        for (int i = 0; i < editTexts.length; i++) {
            editTexts[i].addTextChangedListener(watcher);
        }
    }

    /**
     * 失去焦点时判断输入框是否符合正则
     *
     * @param regular 正则
     */
    public static void editTextsRegularCorrect(final String regular, final OnInputListener listener, final EditText... editTexts) {
        View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                LogUtils.INSTANCE.d("v = " + v);
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    // 此处为失去焦点时的处理内容
                    boolean isComplete = true;
                    for (int i = 0; i < editTexts.length; i++) {
                        Pattern p = Pattern.compile(regular);
                        Matcher m = p.matcher(((EditText) v).getText());
                        if (!m.matches()) {
                            isComplete = false;
                            break;
                        }
                    }
                    listener.onComplete(isComplete);
                }
            }
        };
        for (int i = 0; i < editTexts.length; i++) {
            editTexts[i].setOnFocusChangeListener(onFocusChangeListener);
        }
    }

    /**
     * 判断输入框内容是否全部相同
     */
    public static void editTextsContentEquals(final OnInputListener listener, final EditText... editTexts) {
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean isComplete = true;
                for (int i = 0; i < editTexts.length; i++) {
                    if (!TextUtils.equals(editTexts[i].getText(), s)) {
                        isComplete = false;
                        break;
                    }
                }
                listener.onComplete(isComplete);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        for (int i = 0; i < editTexts.length; i++) {
            editTexts[i].addTextChangedListener(watcher);
        }
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    public interface OnInputListener {
        void onComplete(boolean isComplete);
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isStrNumber(@NonNull String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        return str.matches("[0-9]+");
    }

    /**
     * dp转px
     */
    public static int dptopx(int dp) {
        float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * sp转px
     */
    public static int sptopx(float spValue) {
        float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取状态栏高度
     */
    public static int getStateBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取ShaogoodsToolbar高度
     */
    public static int getToolbarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        result = result + dptopx(50);
        return result;
    }

    /**
     * 设置控件marginTop加上状态栏高度
     */
    public static void setStateBarMarginTop(View view) {
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.topMargin = layoutParams.topMargin + getStateBarHeight(view.getContext());
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件marginTop是Toolbar高度
     */
    public static void setToolbarMarginTop(View view) {
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.topMargin = getToolbarHeight(view.getContext());
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件高度是状态栏高度
     */
    public static void setStatusBarHeight(View view) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height = getStateBarHeight(view.getContext());
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件高度是状态栏高度
     */
    public static void setToolbarHeight(View view) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height = getToolbarHeight(view.getContext());
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件上边距是状态栏高度
     */
    public static void setStatusBarPaddingTop(View view) {
        view.setPadding(view.getPaddingLeft(), getStateBarHeight(view.getContext()), view.getPaddingRight(), view.getPaddingBottom());
    }

    /**
     * 32位MD5加密
     *
     * @param content -- 待加密内容
     * @return
     */
    public static String md5Decode(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }
        //对生成的16字节数组进行补零操作
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 获取图片地址
     */
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 判断APP是否安装
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        if (packages != null) {
            for (int i = 0; i < packages.size(); i++) {
                String pn = packages.get(i).packageName;
                if (pn.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 手机号***显示
     */
    public static String getHideMobile(String phoneNum) {
        if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() > 7) {
            phoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7);
        }
        return phoneNum;
    }

    /**
     * 身份證***显示
     */
    public static String getHideIdCardNumber(String idCardNumber) {
        if (!TextUtils.isEmpty(idCardNumber) && idCardNumber.length() > 14) {
            idCardNumber = idCardNumber.substring(0, 3) + "***********" + idCardNumber.substring(14);
        }
        return idCardNumber;
    }


    /**
     * 返回天时分秒
     *
     * @param second
     * @return
     */
    public static String secondToTime(Context context, long second) {
        long day = second / 86400; // 转天数
        second = second % 86400; // 剩余小时数
        long hours = second / 3600; // 转换小时数
        second = second % 3600; // 剩余秒数
        long minutes = second / 60; // 转换分钟
        second = second % 60; // 剩余秒数
        return String.format(context.getString(R.string.down_time_second_s), String.valueOf(day), (hours >= 10 ? hours : "0" + hours),
                (minutes >= 10 ? minutes : "0" + minutes), (second >= 10 ? second : "0" + second));
    }

    /**
     * 返回时分秒
     *
     * @param second
     * @return
     */
    public static String goodsSecondToTime(Context context, long second) {
        long hours = second / 3600; // 转换小时数
        second = second % 3600; // 剩余秒数
        long minutes = second / 60; // 转换分钟
        second = second % 60; // 剩余秒数
        return (hours >= 10 ? hours : "0" + hours) + ":" + (minutes >= 10 ? minutes : "0" + minutes)
                + ":" + (second >= 10 ? second : "0" + second);
    }

    /**
     * 返回天时分
     *
     * @param second
     * @return
     */
    public static String biddingSecondToTime(Context context, long second) {
        long day = second / 86400; // 转天数
        second = second % 86400; // 剩余小时数
        long hours = second / 3600; // 转换小时数
        second = second % 3600; // 剩余秒数
        long minutes = second / 60; // 转换分钟
        return String.format(context.getString(R.string.down_time_minute_s), String.valueOf(day), (hours >= 10 ? hours : "0" + hours),
                (minutes >= 10 ? minutes : "0" + minutes));
    }


    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public static void showInput(Activity activity, final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 关闭软键盘
     */
    public static void closeInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = activity.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 判断是否成功
     */
    public static boolean isCodeSuccess(String code) {
        if (!TextUtils.isEmpty(code)) {
            return TextUtils.equals(code, "success");
        }
        return false;
    }

    /**
     * unicode转字符串
     *
     * @param string
     * @return
     */
    public static String unicodeToString(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    /**
     * 获取APP时间
     */
    public static String getPhoneTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    /**
     * 获取时间的时间戳
     */
    public static long getTimeStamp(String endTime) {
        if (!TextUtils.isEmpty(endTime)) {
            SimpleDateFormat oldFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date;
            try {
                date = oldFormat.parse(endTime);
                return date.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 获取语言
     */
    public static String getLanguage() {
        String country = Locale.getDefault().getCountry();
        String language = Locale.getDefault().getLanguage();
        if (country.equals("CN") && language.equals("zh")) {
            return "zh_CN";
        } else if ((country.equals("TW") || country.equals("HK") || country.equals("MO")) && language.equals("zh")) {
            return "zh_TW";
        } else {
            return "zh_CN";
        }
    }

    /**
     * 登录页面登录完成，判断是否有跳转页
     */
    public static boolean pushLoginClass(Activity activity, Intent b) {
        String className = b.getStringExtra("targetClass");
        // 有没有推送详情
        if (!TextUtils.isEmpty(className)) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(activity, className));
            intent.putExtras(b);
            activity.startActivity(intent);
            return true;
        }
        return false;
    }

    public static void startLoginPage(Context context, Class clazz) {
        startLoginPage(context, clazz, null);
    }

    /**
     * 跳转需要登录的页面
     */
    public static void startLoginPage(Context context, Class clazz, Bundle bundle) {
        Intent intentFrom = new Intent();
        if (bundle != null) {
            intentFrom.putExtras(bundle);
        }
        // 判断是否登录
        if (ProjectApplication.Companion.isLogin()) {
            intentFrom.setClass(context, clazz);
        } else {
            intentFrom.putExtra("targetClass", clazz.getName());
            intentFrom.setClass(context, LoginActivity.class);
        }
        context.startActivity(intentFrom);
    }

    public static Bitmap loadBitmapFromViewBySystem(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        //获得可视化组件的截图
        return v.getDrawingCache();
    }

    /**
     * 保存图片到本地
     */
    public static void savePicture(final Activity activity, final Bitmap bitmap, final SimpleCallback<String> callback) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String sdCardDir = Environment.getExternalStorageDirectory().getPath() + "/Nayuta/";
                    File dirFile = new File(sdCardDir);
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    final File file = new File(sdCardDir, "my_qr_code.png");
                    if (file.exists()) {
                        file.delete();
                    }
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (out != null) {
                        try {
                            out.flush();
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) callback.onCallback(sdCardDir);
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);//扫描单个文件
                            intent.setData(Uri.fromFile(file));//给图片的绝对路径
                            activity.sendBroadcast(intent);
                        }
                    });
                }
            }).start();
        }
    }

    public static Double stringToDouble(String s) {
        return stringToDouble(s, 0.00);
    }

    public static Double stringToDouble(String s, double defaultValue) {
        try {
            if (TextUtils.isEmpty(s)) {
                return defaultValue;
            }
            defaultValue = Double.valueOf(s.replaceAll("[^\\d.]+", ""));
        } catch (NumberFormatException e) {
            LogUtils.INSTANCE.d("stringToDouble() error = " + s);
        }
        return defaultValue;
    }

    /**
     * 科学计数法转换
     */
    public static String priceTransformation(String d) {
        BigDecimal bd = new BigDecimal(d);
        return bd.toPlainString();
    }

    /**
     * 乘法运算
     */
    public static double multiplication(double price, double exchangeRate) {
        BigDecimal bd1 = new BigDecimal(price);
        BigDecimal bd2 = new BigDecimal(exchangeRate);
        return bd1.multiply(bd2).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
